/**
 * Huisou.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */

package com.chenzehe.hadoop.action;

import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

/**
 * @description
 * 
 * @author chenzehe
 * @email hljuczh@163.com
 * @create 2013-8-1 上午09:36:55
 */

public class WordCount {
	static class MapClass extends Mapper<LongWritable, Text, Text, IntWritable> {
		private Text		word	= new Text();
		final IntWritable	count	= new IntWritable(1);
		
		public void map(LongWritable key, Text value, Context context) {
			StringTokenizer itr = new StringTokenizer(value.toString());
			while (itr.hasMoreTokens()) {
				word.set(itr.nextToken());
				try {
					context.write(word, count);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	static class ReduceClass extends Reducer<Text, IntWritable, Text, IntWritable> {
		private IntWritable	count	= new IntWritable();
		
		public void reduce(Text key, Iterable<IntWritable> values, Context context) {
			int sum = 0;
			for (IntWritable value : values) {
				sum += value.get();
			}
			count.set(sum);
			try {
				context.write(key, count);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
	    String libpath = System.getProperty("java.library.path");  
	    System.out.println("libpath=" + libpath);  
		Configuration conf = new Configuration();
		conf.set("mapred.job.tracker", "master-2:49001");
		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
		if (otherArgs.length != 2) {
			System.err.println("Usage: wordcount <in> <out>");
			System.exit(2);
		}
		Job job = new Job(conf, "my word count");
		job.setJarByClass(WordCount.class);
		job.setMapperClass(MapClass.class);
		// job.setCombinerClass(ReduceClass.class);
		job.setReducerClass(ReduceClass.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
